import React, { Component } from 'react'

import { Carousel, Flex ,Modal,Toast} from 'antd-mobile'

import NavHeader from '../../components/NavHeader'
import HouseItem from '../../components/HouseItem'
import HousePackage from '../../components/HousePackage'

import { bUrl } from '../../utils/url'
import { isAuth } from '../../utils/auth'
import requset  from '../../utils/request'

import styles from './index.module.css'
import axios from 'axios'

// 猜你喜欢
const recommendHouses = [
  {
    id: 1,
    src: bUrl + '/img/message/1.png',
    desc: '72.32㎡/南 北/低楼层',
    title: '安贞西里 3室1厅',
    price: 4500,
    tags: ['随时看房']
  },
  {
    id: 2,
    src: bUrl + '/img/message/2.png',
    desc: '83㎡/南/高楼层',
    title: '天居园 2室1厅',
    price: 7200,
    tags: ['近地铁']
  },
  {
    id: 3,
    src: bUrl + '/img/message/3.png',
    desc: '52㎡/西南/低楼层',
    title: '角门甲4号院 1室1厅',
    price: 4300,
    tags: ['集中供暖']
  }
]

// 百度地图
const BMap = window.BMap

const labelStyle = {
  position: 'absolute',
  zIndex: -7982820,
  backgroundColor: 'rgb(238, 93, 91)',
  color: 'rgb(255, 255, 255)',
  height: 25,
  padding: '5px 10px',
  lineHeight: '14px',
  borderRadius: 3,
  boxShadow: 'rgb(204, 204, 204) 2px 2px 2px',
  whiteSpace: 'nowrap',
  fontSize: 12,
  userSelect: 'none'
}
export default class HouseDetail extends Component {
  state = {
    isLoading: false, // 加载中防止轮播图出问题
    isFavorite: false, // 是否收藏
    houseInfo: {
      // 房屋图片
      houseImg: [],
      // 标题
      title: '',
      // 标签
      tags: [],
      // 租金
      price: 0,
      // 房型
      roomType: '两室一厅',
      // 房屋面积
      size: 89,
      // 装修类型
      renovation: '精装',
      // 朝向
      oriented: [],
      // 楼层
      floor: '',
      // 小区名称
      community: '',
      // 地理位置
      coord: {
        latitude: '39.928033',
        longitude: '116.529466'
      },
      // 房屋配套
      supporting: [],
      // 房屋标识
      houseCode: '',
      // 房屋描述
      description: ''
    }
  }

  componentDidMount() {
    this.getHouseList() 
    this.checkFavorite()
  }

  async getHouseList ()  { // 获取房屋详情数据
    this.setState({
      isLoading: true
    })
    const { params: { id } } = this.props.match
    const {data: res} = await axios.get('http://api-haoke-web.itheima.net/houses/' + id)
    this.setState(_ => {
      return {
        houseInfo: res.body,
        isLoading: false
      }
    })
    const { houseInfo : { community, coord: { latitude, longitude}}} = this.state
    this.renderMap(community, {
      latitude,
      longitude
    })
  }

  // 渲染轮播图结构
  renderSwipers() {
    const {
      houseInfo: { houseImg }
    } = this.state
    return houseImg.map(item => (
      <a
        key={item}
        href="http://itcast.cn"
        style={{
          display: 'inline-block',
          width: '100%',
          height: 252
        }}
      >
        <img
          src={'http://api-haoke-web.itheima.net' + item}
          alt=""
          style={{ width: '100%', verticalAlign: 'top', height:'100%' }}
        />
      </a>
    ))
  }

  // 渲染地图
  renderMap(community, coord) {
    // 传入要展示的名字和经纬度信息
    const { latitude, longitude } = coord

    const map = new BMap.Map('map')
    const point = new BMap.Point(longitude, latitude)
    map.centerAndZoom(point, 17)

    const label = new BMap.Label('', {
      position: point,
      offset: new BMap.Size(0, -36)
    })

    label.setStyle(labelStyle)
    label.setContent(`
      <span>${community}</span>
      <div class="${styles.mapArrow}"></div>
    `)
    map.addOverlay(label)
  }
  async checkFavorite () { // 判断是否收藏
    const { params: { id } } = this.props.match
    if (isAuth()) { // 当登录了在获取
      const { data: res } = await requset('/user/favorites/'+ id,'GET')
      if (res.status === 200) {
        this.setState(_ => { // 修改收藏状态  
          return { 
            isFavorite: res.body.isFavorite
          }
        })
      }
    }
  }
  handleFavorite = async () => { // 收藏或取消收藏房源
    Toast.loading('loading...', 0)
    const { params: { id } } = this.props.match
    const { isFavorite } = this.state
    if (isAuth()) { // 是否登录
      const method = isFavorite ? 'DELETE' : 'POST'
      const { data: res } = await requset('/user/favorites/'+ id, method)
      if (res.status === 200) {
        this.setState(_ =>{
          Toast.hide()
          return {
            isFavorite: !isFavorite
          }
        })
        Toast.info(res.description + '成功', 2)
      }
    } else {
      const alert = Modal.alert
      alert('登录提示', '您还未登录，需要登录之后才能收藏', [
        { text: '取消' },
        { text: '去登陆', onPress: () => {
          this.props.history.push({
              pathname:'/login',
              state: {
                from: this.props.location // 保存当前的路径信息到login的location对象中，他拿到后再进行跳转
              }
          })
        } }
      ])
    }
  }
  render() {
    const { isLoading, isFavorite, houseInfo: {
      community,
      title,
      price,
      roomType,
      size,
      floor,
      oriented,
      supporting,
      description,
      tags
    } } = this.state
    
    return (
      <div className={styles.root}>
        {/* 导航栏 */}
        <NavHeader
          className={styles.navHeader}
          rightContent={[<i key="share" className="iconfont icon-share" />]}
        >
          {community}
        </NavHeader>

        {/* 轮播图 */}
        <div className={styles.slides}>
          {!isLoading ? (
            <Carousel autoplay infinite autoplayInterval={5000}>
              {this.renderSwipers()}
            </Carousel>
          ) : (
            ''
          )}
        </div>

        {/* 房屋基础信息 */}
        <div className={styles.info}>
          <h3 className={styles.infoTitle}>
            {title}
          </h3>
          <Flex className={styles.tags}>
            <Flex.Item>
              {tags.map((x, y) => {
                const styleCss = 'tag' +( y + 1)
                return (<span className={[styles.tag, styles[styleCss]].join(' ')}>
                {x}
              </span>)
              })}
              
            </Flex.Item>
          </Flex>

          <Flex className={styles.infoPrice}>
            <Flex.Item className={styles.infoPriceItem}>
              <div>
                {price}
                <span className={styles.month}>/月</span>
              </div>
              <div>租金</div>
            </Flex.Item>
            <Flex.Item className={styles.infoPriceItem}>
              <div>{roomType}</div>
              <div>房型</div>
            </Flex.Item>
            <Flex.Item className={styles.infoPriceItem}>
              <div>{size}平米</div>
              <div>面积</div>
            </Flex.Item>
          </Flex>

          <Flex className={styles.infoBasic} align="start">
            <Flex.Item>
              <div>
                <span className={styles.title}>装修：</span>
                精装
              </div>
              <div>
                <span className={styles.title}>楼层：</span>
                {floor}
              </div>
            </Flex.Item>
            <Flex.Item>
              <div>
                <span className={styles.title}>朝向：</span>{oriented.join('、')}
              </div>
              <div>
                <span className={styles.title}>类型：</span>普通住宅
              </div>
            </Flex.Item>
          </Flex>
        </div>

        {/* 地图位置 */}
        <div className={styles.map}>
          <div className={styles.mapTitle}>
            小区：
            <span>{community}</span>
          </div>
          <div className={styles.mapContainer} id="map">
            地图
          </div>
        </div>

        {/* 房屋配套 */}
        <div className={styles.about}>
          <div className={styles.houseTitle}>房屋配套</div>
          {/* supporting要展示的房屋配置 */}
          {supporting.length === 0 ? (
              <div className={styles.titleEmpty}>暂无数据</div>
            ) : (
              // HousePackage 组件不传select ,传递list 表示要展示
              <HousePackage list={supporting} />
            )}
        </div>

        {/* 房屋概况 */}
        {/* 写死的 */}
        <div className={styles.set}>
          <div className={styles.houseTitle}>房源概况</div>
          <div>
            <div className={styles.contact}>
              <div className={styles.user}>
                <img src={bUrl + '/img/avatar.png'} alt="头像" />
                <div className={styles.useInfo}>
                  <div>王女士</div>
                  <div className={styles.userAuth}>
                    <i className="iconfont icon-auth" />
                    已认证房主
                  </div>
                </div>
              </div>
              <span className={styles.userMsg}>发消息</span>
            </div>

            <div className={styles.descText}>
              {description || '暂无房屋描述'}
            </div>
          </div>
        </div>

        {/* 推荐 */}
        <div className={styles.recommend}>
          <div className={styles.houseTitle}>猜你喜欢</div>
          <div className={styles.items}>
            {recommendHouses.map(item => (
              <HouseItem {...item} key={item.id} />
            ))}
          </div>
        </div>

        {/* 底部收藏按钮 */}
        <Flex className={styles.fixedBottom}>
          <Flex.Item  onClick={this.handleFavorite}>
            <img
              src={bUrl + '/img/unstar.png'}
              className={styles.favoriteImg}
              alt="收藏"
            />
            <span className={styles.favorite}>{isFavorite? '已收藏': '收藏'}</span>
          </Flex.Item>
          <Flex.Item>在线咨询</Flex.Item>
          <Flex.Item>
            <a href="tel:400-618-4000" className={styles.telephone}>
              电话预约
            </a>
          </Flex.Item>
        </Flex>
      </div>
    )
  }
}
